package com.zhsecurity.userdetails;

import com.zhsecurity.Admin;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

public class MemoryUserDetailsServiceImpl implements UserDetailsService {
    private List<Admin> admins = new ArrayList<Admin>();

    public MemoryUserDetailsServiceImpl(List<Admin> admins) {
        this.admins = admins;
    }

    public MemoryUserDetailsServiceImpl() {
    }

    public void setAdmins(List<Admin> admins) {
        this.admins = admins;
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (admins == null || admins.size() == 0) {
            throw new UsernameNotFoundException(username);
        }
        Admin admin = getAdminByUsername(username);
        if (admin == null) {
            throw new UsernameNotFoundException(username);
        }

        boolean enabled = false;
        if (admin.getEnabled().equals("1")) {
            enabled = true;
        }
        List<? extends GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        User user = new User(admin.getUsername(), admin.getPassword(), enabled, true, true, true, authorities);
        return user;
    }

    private Admin getAdminByUsername(String username) {
        Admin result = null;
        for (Admin admin : admins) {
            if (username.equals(admin.getUsername())) {
                result = admin;
                break;
            }
        }
        return result;
    }
}
